// 2023-03-20 15:13:51

import { AxiosError, AxiosResponse, AxiosRequestConfig } from "axios";
import axios from "axios";
import { CODE, baseURL } from '@/config/data.config.js'

// 2023-03-22 19:08:36 请求拦截器，每次请求带上token
axios.interceptors.request.use((config) => {
    let Info = null
    try {
        Info = JSON.parse(window.localStorage.getItem('HuiLY'))
    } catch (error) {
        console.error(error);
    }
    let token = Info ? Info.token : 'huily'
    config.headers.Authorization = `Bearer ${token}`;
    return config;
}, err => {
    console.error(err)
    return Promise.reject(err)
})

// 2023-03-22 19:10:01 响应拦截器，每次刷新token
axios.interceptors.response.use(
    response => {
        const token = response.headers.token ? response.headers.token : null;
        try {
            let info = JSON.parse(window.localStorage.getItem('HuiLY'))
            if (info) {
                info.token = token
            } else {
                info = {
                    token
                }
            }
            window.localStorage.setItem('HuiLY', JSON.stringify(info))
        } catch (error) {
            console.log(error);
        }
        return response
    },
    /**
     * 状态码超过2xx触发 即使是超过范围也是会返回对象
     * @param {AxiosError} err 
     */
    err => {
        return Promise.reject(err.response)
    }
)

/**
 * @param {AxiosResponse} response 
 * @returns {Promise<AxiosResponse>}
 */
function CheckCode(response) {
    return new Promise((resolve, reject) => {
        const code = response.data.code;
        if (code === CODE.CODE_TOKEN) {
            console.log('请重新登录!');
            reject(response)
        }
        if (code == CODE.CODE_FAIL) {
            reject(response)
        }
        if (code == CODE.CODE_OK) {
            resolve(response);
        } else {
            reject(response)
        }
    })
}

/**
 * GET 请求方法，params一定需要，这个会写进query里面
 * @param {URL} url 
 * @param {JSON | Object} params 
 * @param {Object} config 
 * @returns {Promise<AxiosResponse>}
 */
export async function GET(url, params = {}, config = {}) {
    try {
        url = baseURL + url;
        config.params = params
        const response = await axios.get(url, config);
        return await CheckCode(response);
    } catch (error) {
        // 还是把response传回去，但是处理函数不同
        return Promise.reject(error)
    }
}
/**
 * POST 请求方法，params一定需要，这个会写进body里面
 * @param {URL} url 
 * @param {JSON | Object} params 
 * @param {Object} config 
 * @returns {Promise<AxiosResponse>}
 */
export async function POST(url, params, config = {}) {
    try {
        url = baseURL + url;
        const respone = await axios.post(url, params, config);
        return await CheckCode(respone);
    } catch (error) {
        return Promise.reject(error)
    }
}

/**
 * 
 * @param {URL} url 
 * @param {JSON | {model:JSON,columns:JSON}} params 
 * @param {*} config 
 * @returns {Promise<AxiosResponse>}
 */
export async function PUT(url, params, config = {}) {
    try {
        url = baseURL + url;
        return await axios.put(url, params, config);
    } catch (error) {
        return Promise.reject(error)
    }
}
/**
 * @param {*} url 
 * @param {*} params 
 * @param {AxiosRequestConfig<any>} config 
 * @returns 
 */
export async function DELETE(url, params, config = {}) {
    try {
        url = baseURL + url;
        config.data = params
        const respone = await axios.delete(url, config);
        return await CheckCode(respone);
    } catch (error) {
        return Promise.reject(error)
    }
}